<template>
    <div class="login">
       <el-form :model="form" :rules="rules" ref="form" class="container">
           <el-form-item >
                <div class="avatar">
                    <img src="../assets/10.jpg" alt="head" style="width:120px; height:120px">
                </div>
            </el-form-item>
            <!-- 用户名 -->
            <el-form-item label="用户名" prop="username">
                <el-input placeholder="用户名" v-model="form.username" ></el-input>
            </el-form-item>
            <!-- 密码 -->
            <el-form-item label="密码" prop="password">
                <el-input type="password" placeholder="密码" v-model="form.password" @keydown.enter.native="submitForm('form')"></el-input>
            </el-form-item>
            <!-- 登陆 -->
            <el-form-item>
                <el-button type="primary" @click="submitForm('form')" class="btn-primary">登陆</el-button>
            </el-form-item>
            </el-form>
    </div>
</template>

<script>
import { checkUser } from '@/api'
export default {
  data() {
    return {
      form: {
        username: "",
        password: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }]
      }
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
            checkUser(this.form).then(res => {
                // 如果成功跳转，就将token保存到localStorage
                if(res.meta.status === 200){
                    localStorage.setItem('mytoken',res.data.token)
                    // 跳转
                    this.$router.push({name: 'home'})
                }else{
                    // 如果失败，展示提示信息
                    this.$message({
                        type: 'error',
                        message: res.meta.msg
                    })
                }
            })
        } else {
          this.$message.error("数据不完整！！")
        }
      });
    }
  }
};
</script>
<style scoped>
    .login{
        position: fixed;
        width: 100%;
        height: 100%;
        background-color: #2f4050;
    }
    .container{
        position: absolute;
        left: 0;
        right: 0;
        width: 400px;
        padding: 0 40px 15px 40px;
        margin: 200px auto;
        background-color: #fff;
        border-radius: 10px;    
    }
    .avatar{
        overflow: hidden;
        position: absolute;
        top: -110px;
        left: 50%;
        width: 120px;
        height: 120px;
        transform: translateX(-50%);
        border-radius: 50%;
        border: 10px solid #fff;
        box-shadow: 0 1px 2px 2px #ccc;
    }
    .btn-primary{
        width: 100%;
    }
</style>
